import 'package:awak/common/utils/util_text.dart';
import 'package:awak/common/utils/util_toast.dart';
import 'package:awak/common/values/svg.dart';
import 'package:awak/common/models/content.dart';
import 'package:awak/common/repository/content_repository.dart';
import 'package:awak/common/repository/user_repository.dart';
import 'package:awak/page/community/topic_data_holder.dart';
import 'package:awak/page/community/content_data_holder.dart';
import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'dart:io';

class ContentReleasePage extends StatefulWidget {
  const ContentReleasePage({super.key});

  @override
  State<ContentReleasePage> createState() => _ContentReleasePageState();
}

class _ContentReleasePageState extends State<ContentReleasePage> {
  final TextEditingController _contentController = TextEditingController();
  final ContentRepository _contentRepository = ContentRepository();
  final UserRepository _userRepository = UserRepository();
  String? _selectedImagePath;
  String? _selectedTopicLabel;
  List<String> _availableTopicLabels = [];

  @override
  void initState() {
    super.initState();
    _loadAvailableTopics();
  }

  @override
  void dispose() {
    _contentController.dispose();
    super.dispose();
  }

  // 加载可用的主题标签
  void _loadAvailableTopics() {
    final topics = TopicDataHolder.allTopics;
    setState(() {
      _availableTopicLabels = topics.map((topic) => topic.label).toList();
      if (_availableTopicLabels.isNotEmpty) {
        _selectedTopicLabel = _availableTopicLabels.first;
      }
    });
  }

  // 选择图片
  Future<void> _pickImage() async {
    final List<AssetEntity>? result = await AssetPicker.pickAssets(
      context,
      pickerConfig: const AssetPickerConfig(
        maxAssets: 1,
        requestType: RequestType.image,
      ),
    );

    if (result != null && result.isNotEmpty) {
      final file = await result.first.file;
      if (file != null) {
        setState(() {
          _selectedImagePath = file.path;
        });
      }
    }
  }

  // 发布内容
  Future<void> _releaseContent() async {
    final contentText = _contentController.text.trim();

    if (contentText.isEmpty) {
      AwakToast.showCustomToast(context, 'Please enter your content');
      return;
    }

    if (_selectedTopicLabel == null) {
      AwakToast.showCustomToast(context, 'Please select a topic');
      return;
    }

    // 根据选择的标签找到对应的主题
    final selectedTopic = TopicDataHolder.allTopics
        .where((topic) => topic.label == _selectedTopicLabel)
        .firstOrNull;

    if (selectedTopic?.id == null) {
      AwakToast.showCustomToast(context, 'Invalid topic selected');
      return;
    }

    // 获取当前登录用户ID
    final currentUserId = _userRepository.currentUser?.id;
    if (currentUserId == null) {
      AwakToast.showCustomToast(context, 'Please login first');
      return;
    }

    // 使用默认图片如果没有选择
    final contentPicture = _selectedImagePath ?? 'assets/images/default_content.png';

    final content = Content(
      picture: contentPicture,
      description: contentText,
      userId: currentUserId,
      topicId: selectedTopic!.id!,
      publishedAt: DateTime.now(),
    );

    try {
      // 保存内容到数据库
      final savedContent = await _contentRepository.createContent(content);

      // 更新ContentDataHolder
      ContentDataHolder.allContents.add(savedContent);

      if (mounted) {
        AwakToast.showCustomToast(context, 'Content released successfully!');

        // 返回到社区页面，并传递成功标志
        Beamer.of(context).beamBack();
      }
    } catch (e) {
      if (mounted) {
        AwakToast.showCustomToast(context, 'Failed to release content: $e');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            colors: [Color(0xFFD7F349), Color(0xFFFFFABA)],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
          ),
        ),
        child: SafeArea(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 顶部导航栏
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 16.h),
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    Align(
                      alignment: Alignment.centerLeft,
                      child: GestureDetector(
                        onTap: () => Beamer.of(context).beamBack(),
                        child: Icon(AwakSvg.back),
                      ),
                    ),
                    Center(
                      child: Text('RELEASE', style: AwakText.titleStyle),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 30.h),
              
              // Content输入框
              Center(
                child: Stack(
                  clipBehavior: Clip.none,
                  children: [
                    Container(
                      margin: EdgeInsets.symmetric(horizontal: 12.w),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(16.r),
                        border: Border.all(color: Colors.black, width: 2.w),
                      ),
                      child: TextField(
                        controller: _contentController,
                        maxLines: 6,
                        decoration: InputDecoration(
                          hintText: 'Write A Paragraph That You Think Is Good!',
                          hintStyle: AwakText.body14Style.copyWith(
                            color: Colors.black.withValues(alpha: 0.3),
                          ),
                          border: InputBorder.none,
                          contentPadding: EdgeInsets.only(
                            bottom: 12.h,
                            left: 12.w,
                            right: 12.w,
                            top: 24.h,
                          ),
                        ),
                      ),
                    ),
                    Positioned(
                      top: -25.h,
                      left: 160.w,
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 12.w,
                          vertical: 10.h,
                        ),
                        decoration: BoxDecoration(
                          color: const Color(0xFFF0F44A),
                          borderRadius: BorderRadius.circular(12.r),
                          border: Border.all(color: Colors.black, width: 2.w),
                        ),
                        child: Text(
                          'Content',
                          style: AwakText.body16Style.copyWith(
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 50.h),
              
              // Topic Label选择
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 18.w),
                child: Text(
                  'Topic Label',
                  style: TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 18.sp,
                  ),
                ),
              ),
              SizedBox(height: 12.h),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 18.w),
                child: Wrap(
                  spacing: 12.w,
                  runSpacing: 8.h,
                  children: _availableTopicLabels.map((label) {
                    final isSelected = label == _selectedTopicLabel;
                    return GestureDetector(
                      onTap: () {
                        setState(() {
                          _selectedTopicLabel = label;
                        });
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 16.w,
                          vertical: 8.h,
                        ),
                        decoration: BoxDecoration(
                          color: isSelected ? const Color(0xFFD7F349) : Colors.white,
                          borderRadius: BorderRadius.circular(20.r),
                          border: Border.all(
                            color: Colors.black,
                            width: isSelected ? 2.w : 1.w,
                          ),
                        ),
                        child: Text(
                          label,
                          style: AwakText.body14Style.copyWith(
                            fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                          ),
                        ),
                      ),
                    );
                  }).toList(),
                ),
              ),
              SizedBox(height: 30.h),
              
              // Topic Avatar选择
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 18.w),
                child: Text(
                  'Topic Avatar',
                  style: TextStyle(
                    fontWeight: FontWeight.w600,
                    fontSize: 18.sp,
                  ),
                ),
              ),
              SizedBox(height: 12.h),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 18.w),
                child: Row(
                  children: [
                    GestureDetector(
                      onTap: _pickImage,
                      child: Container(
                        width: 56.w,
                        height: 56.h,
                        decoration: BoxDecoration(
                          color: Colors.black12,
                          borderRadius: BorderRadius.circular(12.r),
                          border: Border.all(color: Colors.black, width: 2.w),
                        ),
                        child: _selectedImagePath != null
                            ? ClipRRect(
                                borderRadius: BorderRadius.circular(10.r),
                                child: Image.file(
                                  File(_selectedImagePath!),
                                  fit: BoxFit.cover,
                                ),
                              )
                            : Icon(
                                Icons.camera_alt,
                                size: 24.sp,
                                color: Colors.black54,
                              ),
                      ),
                    ),
                  ],
                ),
              ),
              
              Spacer(),
              
              // Confirm按钮
              Padding(
                padding: EdgeInsets.all(18.w),
                child: SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    onPressed: _releaseContent,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: const Color(0xFF8FE53F),
                      foregroundColor: Colors.black,
                      padding: EdgeInsets.symmetric(vertical: 16.h),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12.r),
                        side: BorderSide(color: Colors.black, width: 2.w),
                      ),
                    ),
                    child: Text(
                      'Confirm',
                      style: AwakText.body16Style.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
